package com.gosuncn.zfysdk.demo.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.fragment.NavHostFragment;

import com.gosuncn.zfyfw.service.GSFWManager;
import com.gosuncn.zfysdk.demo.R;
import com.gosuncn.zfysdk.demo.base.BaseFragment;
import com.gosuncn.zfysdk.demo.bean.FormEntity;
import com.gosuncn.zfysdk.demo.databinding.FragmentHomeBinding;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wzq.mvvmsmart.http.DownLoadManager;
import com.wzq.mvvmsmart.http.download.ProgressCallBack;
import com.wzq.mvvmsmart.utils.KLog;
import com.wzq.mvvmsmart.utils.ToastUtils;

import io.reactivex.functions.Consumer;
import okhttp3.ResponseBody;

public class MainFragment extends BaseFragment<FragmentHomeBinding, MainViewModel> {



    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_home;
    }

    @Override
    public int initVariableId() {
        return com.gosuncn.zfysdk.demo.BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        binding.setPresenter(new Presenter());
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //注册监听相机权限的请求
        viewModel.requestPermissions.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                KLog.d(TAG, "onChanged value: " + aBoolean);
                requestPermissions();
            }
        });

        //注册文件下载的监听
        viewModel.loadUrlEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String url) {
                downFile(url);
            }
        });

    }

    private Handler mHandler;
    @Override
    public void onResume() {
        super.onResume();
        KLog.d(TAG, "onResume thread: " + Thread.currentThread().getName());
        mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                viewModel.requestPermissions.call();
                KLog.d(TAG, "run thread: " + Thread.currentThread().getName());
            }
        }, 400);

        ((AppCompatActivity)getActivity()).setTitle(R.string.app_name);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        KLog.d(TAG, "onCreate thread: " + Thread.currentThread().getName());
    }

    /**
     * 封装布局中的点击事件儿;
     */
    public class Presenter {

        //应用服务
        public void onAppServiceClicked() {
            NavHostFragment
                    .findNavController(MainFragment.this)
                    .navigate(R.id.action_homeFragment_to_AppServiceFragment);
        }

        //硬件管控
        public void onHwMgrClicked() {
            GSFWManager.startDialerActivity(getActivity());
/*            NavHostFragment
                    .findNavController(MainFragment.this)
                    .navigate(R.id.action_homeFragment_to_HwMgrFragment);*/
        }

        //终端基本功能
        public void onDeviceBaseFuncMgrClicked() {
//            startActivity(TabBarActivity.class);
            NavHostFragment
                    .findNavController(MainFragment.this)
                    .navigate(R.id.action_homeFragment_to_DeviceBaseFuncMgrFragment);
        }

        //终端应用
        public void onAppMgrClicked() {
//            ToastUtils.showShort("点击跳转viewpager");
            NavHostFragment
                    .findNavController(MainFragment.this)
                    .navigate(R.id.action_homeFragment_to_AppMgrFragment);
        }


        //监测采集
        public void onMonitorMgrClicked() {
//            //模拟一个修改的实体数据
//            FormEntity entity = new FormEntity();
//            entity.setId("12345678");
//            entity.setName("wzq");
//            entity.setBir("2020年08月08日");
//            entity.setMarry(true);
//            //传入实体数据
//            Bundle mBundle = new Bundle();
//            mBundle.putParcelable("entity", entity);
            NavHostFragment
                    .findNavController(MainFragment.this)
                    .navigate(R.id.action_homeFragment_to_MonitorMgrFragment/*, mBundle*/);
        }

        //远程控制和配置
        public void onRemoteControlClicked() {
            NavHostFragment
                    .findNavController(MainFragment.this)
                    .navigate(R.id.action_homeFragment_to_RemoteControlFragment);
        }

        //应用权限
        public void onAppPermissionClicked() {
            NavHostFragment
                    .findNavController(MainFragment.this)
                    .navigate(R.id.action_homeFragment_to_AppPermissionFragment);
        }

        //权限申请
        public void permissionsClick() {
            viewModel.requestPermissions.call();
        }

        //全局异常捕获
        public void exceptionClick() {
            //伪造一个异常
            Integer.parseInt("test");
        }

        //文件下载
        public void fileDownLoadClick() {
            viewModel.loadUrlEvent.setValue("http://gdown.baidu.com/data/wisegame/a2cd8828b227b9f9/neihanduanzi_692.apk");

        }

    }

    /**
     * 请求相机权限
     */
    @SuppressLint("CheckResult")
    private void requestPermissions() {
//        ToastUtils.showShort("请求权限");
        //请求打开相机权限
        RxPermissions rxPermissions = new RxPermissions(getActivity());
//        rxPermissions.request(Manifest.permission.CAMERA,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.READ_PHONE_STATE)
//                .subscribe(new Consumer<Boolean>() {
//                    @Override
//                    public void accept(Boolean aBoolean) throws Exception {
//                        if (aBoolean) {
//                            ToastUtils.showShort("权限已打开");
//                        } else {
//                            ToastUtils.showShort("权限被拒绝");
//                            getActivity().finish();
//                        }
//                    }
//                });

        rxPermissions.requestEachCombined(Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
//                            ToastUtils.showShort("权限已打开");
                        } else {
                            ToastUtils.showShort("权限被拒绝");
                            getActivity().finish();
                        }
                    }
                });
    }

    private void downFile(String url) {
        String destFileDir = getActivity().getApplication().getCacheDir().getPath();
        KLog.e("destFileDir--" + destFileDir);
        String destFileName = System.currentTimeMillis() + ".apk";
        final ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下载...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        /**
         * ProgressCallBack构造方法中，LiveEventBus监听进度改变，调用ProgressCallBack的progress方法设置进度
         */
        DownLoadManager.getInstance().load(url, new ProgressCallBack<ResponseBody>(MainFragment.this, destFileDir, destFileName) {
            @Override
            public void onStart() {
                super.onStart();
                KLog.e("下载--onStart");
            }

            @Override
            public void onSuccess(ResponseBody responseBody) {
                KLog.e("下载--onSuccess");
                ToastUtils.showShort("文件下载完成！");
            }

            @Override
            public void progress(final long progress, final long total) {
                KLog.e("下载--progress");
                progressDialog.setMax((int) total);
                progressDialog.setProgress((int) progress);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtils.showShort("文件下载失败！");
                progressDialog.dismiss();
            }

            @Override
            public void onCompleted() {
                progressDialog.dismiss();
                KLog.e("下载--onCompleted");
            }
        });
    }
}
